import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Card, Cascader, InputNumber, message, Spin, Switch, Tag, Tooltip } from 'antd';
import { useEffect, useState } from 'react';
import cityCode from '@/components/assets/citycode.json';
import { nestedCityCode } from '@/components/assets/nestedCityCode';
import { logisticsConfigPages } from '../config/service';
import { logisticsSearchPages } from '../search/service';
import type { searchTypeList } from '../search/data';
import type { searchConfigInfo } from './data';
import CountDetail from './countDetail';
import { InfoCircleOutlined } from '@ant-design/icons';

export default () => {
  const [dataSource, setDataSource] = useState<any>();
  const [primaryCity, setPrimaryCity] = useState<string[]>([]);
  const [weight, setWeight] = useState<number>(0);
  const [pickUp, setPickUp] = useState<boolean>(false);
  const [searchData, setSearchData] = useState<searchTypeList[]>();
  const [countPrice, setCountPrice] = useState<{ weight: number; cityName: string[] }>({
    weight: 0,
    cityName: [],
  });
  // const []
  const [loading, setLoading] = useState<boolean>(false);
  const [contrast, setContrast] = useState<any>([]);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailData, setDetailData] = useState<searchConfigInfo>();
  //获取物流信息
  useEffect(() => {
    const logisticsData: searchTypeList[] = [];
    //获取对应城市信息的接口
    const sub = (area: string) => {
      if (area.endsWith('县') || area.endsWith('区')) {
        if (area.startsWith('宁夏')) {
          return '宁夏';
        } else if (area.startsWith('广西')) {
          return '广西';
        } else if (area.startsWith('新疆')) {
          return '新疆';
        } else if (area.startsWith('内蒙古')) {
          return '内蒙古';
        } else if (area.startsWith('云南')) {
          return '云南';
        }
        return area;
      } else {
        return area.substring(0, area.length - 1);
      }
    };
    countPrice.cityName.map((item) =>
      logisticsSearchPages({
        page: '1',
        pageSize: '1000',
        area: sub(item),
      }).then((res) => {
        if (res.data) {
          res.data.map((e) => {
            if (e != undefined) logisticsData.push(e);
          });
          setSearchData(logisticsData);
        }
      }),
    );
  }, [countPrice]);

  //重量进位至下一个0.5
  const reviseWeight = (w: number) => {
    if (w <= 100) {
      if (Number((w % 1).toFixed(2)) < 0.5 && Number((w % 1).toFixed(2)) > 0) {
        return Math.round(w) + 0.5;
      } else {
        return w;
      }
    } else {
      return w;
    }
  };

  const countSum = (record: searchConfigInfo) => {
    let code = '';
    for (const x in cityCode) {
      if (cityCode[x].includes(record.area[0])) {
        code = x;
      }
    }
    if (
      pickUp &&
      record.weight > 50 &&
      (record.logisticsName == '京东特快重货' || record.logisticsName == '特快零担')
    ) {
      if (code.startsWith('33')) {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.provinceDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2)) + 40;
            } else if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2) + 40,
              );
            } else {
              return (
                Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2)) + 40
              );
            }
          } else {
            if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2) + 40,
              );
            } else {
              return (
                Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2)) + 40
              );
            }
          }
        } else {
          return 0;
        }
      } else {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.outsideDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2)) + 40;
            } else if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
                ) + 40
              );
            } else {
              return (
                Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2)) + 40
              );
            }
          } else {
            if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
                ) + 40
              );
            } else {
              return (
                Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2)) + 40
              );
            }
          }
        } else {
          return 0;
        }
      }
    } else if (
      pickUp &&
      record.weight > 140 &&
      (record.logisticsName == '京东特快重货' || record.logisticsName == '特快零担')
    ) {
      if (code.startsWith('33')) {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.provinceDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2)) + 0.3 * record.weight;
            } else if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2),
                ) +
                0.3 * record.weight
              );
            } else {
              return (
                Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2)) +
                0.3 * record.weight
              );
            }
          } else {
            if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2),
                ) +
                0.3 * record.weight
              );
            } else {
              return (
                Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2)) +
                0.3 * record.weight
              );
            }
          }
        } else {
          return 0;
        }
      } else {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.outsideDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2)) + 0.3 * record.weight;
            } else if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
                ) +
                0.3 * record.weight
              );
            } else {
              return (
                Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2)) +
                0.3 * record.weight
              );
            }
          } else {
            if (record?.shippingRules == 2) {
              return (
                Number(
                  ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
                ) +
                0.3 * record.weight
              );
            } else {
              return (
                Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2)) +
                0.3 * record.weight
              );
            }
          }
        } else {
          return 0;
        }
      }
    } else {
      if (code.startsWith('33')) {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.provinceDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2));
            } else if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2),
              );
            } else {
              return Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2));
            }
          } else {
            if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.provinceDiscount) / 10).toFixed(2),
              );
            } else {
              return Number((((record?.price / 100) * record.provinceDiscount) / 10).toFixed(2));
            }
          }
        } else {
          return 0;
        }
      } else {
        if (record.price) {
          if (record.chargeType == 2) {
            if (((record?.price / 100) * record.outsideDiscount) / 10 <= record?.lowCharge / 100) {
              return Number((record?.lowCharge / 100).toFixed(2));
            } else if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
              );
            } else {
              return Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2));
            }
          } else {
            if (record?.shippingRules == 2) {
              return Number(
                ((Math.round(record?.price / 100) * record.outsideDiscount) / 10).toFixed(2),
              );
            } else {
              return Number((((record?.price / 100) * record.outsideDiscount) / 10).toFixed(2));
            }
          }
        } else {
          return 0;
        }
      }
    }
  };
  //物流计算
  useEffect(() => {
    //获取物流配置信息
    if (searchData != undefined) {
      logisticsConfigPages({ page: 1, pageSize: 1000 }).then((res) => {
        if (res.data) {
          const configData = res.data;
          const segmented: searchConfigInfo[] = []; //分段收费数组
          const segment: searchConfigInfo[] = []; //对段收费数组
          // console.log('查询信息', searchData);
          // console.log('重量数据', countPrice);
          // console.log('配置信息', configData);
          configData.map((config) => {
            searchData?.map((item) => {
              if (config._id == item.logisticsConfig.id) {
                if (config.chargeWay == 1) {
                  if (config.weightRules == 2) {
                    segmented.push({
                      ...config,
                      weight: Math.round(countPrice.weight),
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  } else if (config.weightRules == 3) {
                    segmented.push({
                      ...config,
                      weight: reviseWeight(countPrice.weight),
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  } else {
                    segmented.push({
                      ...config,
                      weight: countPrice.weight,
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  }
                } else {
                  if (config.weightRules == 2) {
                    segment.push({
                      ...config,
                      weight: Math.round(countPrice.weight),
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  } else if (config.weightRules == 3) {
                    segmented.push({
                      ...config,
                      weight: reviseWeight(countPrice.weight),
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  } else {
                    segment.push({
                      ...config,
                      weight: countPrice.weight,
                      area: item.area,
                      lowCharge: item.lowCharge,
                      weightPrice: item.weightPrice,
                    });
                  }
                }
              }
            });
          });
          //物流计算公式
          //分段收费
          const segmentedBilling = () =>
            segmented.map((item) => {
              for (let i = 0, Billing = 0; i < item.weightPrice.length; i++) {
                if (i == 0 && item.startingWeight != 0) {
                  Billing += item.weightPrice[i];
                  if (item.weight <= item.startingWeight) {
                    return { ...item, price: Billing };
                  }
                } else if (i == 1) {
                  if (item.weightPrice.length == 2 && item.startingWeight == 0) {
                    return {
                      ...item,
                      price: item.weight * item.weightPrice[i],
                    };
                  }
                  if (item.weight <= item.weightInterval[i - 1]) {
                    return {
                      ...item,
                      price: Billing + (item.weight - item.startingWeight) * item.weightPrice[i],
                    };
                  } else {
                    Billing +=
                      (item.weightInterval[i - 1] - item.startingWeight) * item.weightPrice[i];
                  }
                } else if (
                  i == item.weightPrice.length - 1 &&
                  item.weight >= item.weightInterval[i - 2]
                ) {
                  Billing += (item.weight - item.weightInterval[i - 2]) * item.weightPrice[i];
                  return { ...item, price: Billing };
                } else {
                  if (item.weight <= item.weightInterval[i - 1]) {
                    return {
                      ...item,
                      price:
                        Billing + (item.weight - item.weightInterval[i - 2]) * item.weightPrice[i],
                    };
                  }
                  Billing +=
                    (item.weightInterval[i - 1] - item.weightInterval[i - 2]) * item.weightPrice[i];
                }
              }
            });

          //对段加首重
          const segmentBilling = () =>
            segment.map((item) => {
              for (let i = 0; i < item.weightPrice.length; i++) {
                if (item.weight < item.startingWeight)
                  return { price: item.weightPrice[0], ...item };
                else if (item.weight < item.weightInterval[0])
                  return {
                    price:
                      item.weightPrice[0] +
                      (item.weight - item.startingWeight) * item.weightPrice[1],
                    ...item,
                  };
                else if (
                  i == item.weightPrice.length - 1 &&
                  item.weight > item.weightInterval[i - 2]
                )
                  return {
                    price:
                      item.weightPrice[0] +
                      (item.weight - item.startingWeight) * item.weightPrice[i],
                    ...item,
                  };
                else {
                  if (item.weight <= item.weightInterval[i - 1]) {
                    return {
                      price:
                        item.weightPrice[0] +
                        (item.weight - item.startingWeight) * item.weightPrice[i],
                      ...item,
                    };
                  }
                }
              }
            });

          const searchConfig = segmentBilling().concat(segmentedBilling());
          const Contrast: any = [];
          searchConfig.map((item) => {
            if (item) Contrast.push({ price: countSum(item), name: item.logisticsName });
          });

          Contrast.sort(function (a: { price: number }, b: { price: number }) {
            return a.price - b.price;
          }).join(',');
          setContrast(Contrast);
          setDataSource(searchConfig);
          setLoading(false);
        } else {
          message.error('物流配置请求失败');
        }
      });
    }
  }, [searchData]);

  const columns2: ProColumns<searchConfigInfo>[] = [
    {
      title: '物流总价',
      dataIndex: 'price',
      tooltip: '默认按照升序价格排序',
      width: '150px',
      ellipsis: true,
      render: (_, record) => {
        if (countSum(record)) {
          if (countSum(record) == contrast[0].price) {
            return <Tag color="green">{countSum(record) + '元'}</Tag>;
          }
          return <Tag color="purple">{countSum(record) + '元'}</Tag>;
        } else {
          return '-';
        }
      },
      defaultSortOrder: 'ascend',
      sorter: {
        compare: (a, b) => {
          return countSum(a) - countSum(b);
        },
        multiple: 500,
      },
    },
    {
      title: '物流名称',
      dataIndex: 'logisticsName',
      search: false,
      ellipsis: true,
    },
    {
      title: '出发地',
      dataIndex: 'startArea',
      search: false,
      ellipsis: true,
      render: () => <div>杭州市</div>,
    },
    {
      title: '重量',
      dataIndex: 'weight',
      search: false,
      ellipsis: true,
      render: (_, record) => {
        return record.weight + 'kg';
      },
    },
    {
      title: '查询区域',
      dataIndex: 'area',
      ellipsis: true,
      render: (_, record) => {
        let areaSum = '';
        record.area?.map((item: string) => {
          areaSum += item + '/';
        });
        if (areaSum.endsWith('/')) {
          areaSum = areaSum.substring(0, areaSum.length - 1);
        }
        return areaSum;
      },
    },
    {
      title: '计价规则',
      dataIndex: 'priceInfo',
      search: false,
      ellipsis: true,
      render: (_, render) => {
        return (
          <a
            onClick={() => {
              setDetailVisible(true);
              setDetailData(render);
            }}
          >
            查看
          </a>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <Card style={{ width: '100%', marginBottom: 17 }}>
        <>
          <span>目的城市：</span>
          <Cascader
            showSearch={true}
            style={{ width: '30vw' }}
            placeholder="选择所在地区(支持关键字搜索)"
            onChange={(e: any[]) => {
              setPrimaryCity(e);
            }}
            fieldNames={{ label: 'name', value: 'name', children: 'children' }}
            options={nestedCityCode}
          />
          <span style={{ marginLeft: 30 }}>重量：</span>
          <InputNumber
            style={{ width: '15vw' }}
            min={0}
            precision={2}
            onChange={(e: any) => {
              setWeight(e);
            }}
            addonAfter={'kg'}
          ></InputNumber>
          <span style={{ marginLeft: 30 }}>
            上楼费{' '}
            <Tooltip title="目的地为一楼，不增加上楼费；如果不是一楼，要计算上楼费用">
              <InfoCircleOutlined />
            </Tooltip>
            ：
          </span>
          <Switch
            onChange={(e) => {
              setPickUp(e);
            }}
            style={{ marginBottom: 4 }}
            checkedChildren="开启"
            unCheckedChildren="关闭"
          />
          <Button
            type="primary"
            onClick={() => {
              if (weight != 0) {
                if (primaryCity[0] != undefined) {
                  setCountPrice({ weight: weight, cityName: primaryCity });
                  setLoading(true);
                } else {
                  message.info('目的城市不能为空');
                }
              } else {
                message.info('重量需大于0');
              }
            }}
            style={{ marginLeft: 30 }}
          >
            计算
          </Button>
        </>
      </Card>
      <Spin spinning={loading}>
        <ProTable
          scroll={{ x: true }}
          headerTitle="物流价格计算结果"
          tooltip="如果计算结果中同一物流公司的目的地省和市同时出现，优先取目的地为市的物流计算结果"
          columns={columns2}
          rowKey="index"
          pagination={false}
          search={false}
          dataSource={dataSource}
        />
      </Spin>
      {detailVisible && detailData && (
        <CountDetail
          detailData={detailData}
          visible={detailVisible}
          onClose={() => {
            setDetailData(undefined);
            setDetailVisible(false);
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};
